package cn.qing.controller;

import cn.qing.pojo.Product;
import cn.qing.service.ProductService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    ProductService productService;

    /**
     * 查找全部产品
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("findAll")
    public ModelAndView findAll(
            @RequestParam(name = "page",defaultValue = "1") Integer page,
            @RequestParam(name = "size",defaultValue = "5") Integer size){

        ModelAndView mv = new ModelAndView();

        List<Product> productList = productService.findAll(page, size);

        //设置视图页面 和 模型数据
        PageInfo<Product> pageInfo = new PageInfo<>(productList);

        mv.addObject("pageInfo",pageInfo);
        mv.setViewName("product-list");
        return mv;
    }

    /**
     * 新增产品
     * @param product
     * @return
     */
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public String save(Product product){

        productService.save(product);
        return "redirect:findAll.do";
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @RequestMapping("deleteById")
    public String deleteById(@RequestParam Integer id){

        productService.deleteById(id);
        return "redirect:findAll.do";
    }

    /**
     * 详情
     * @param id
     */
    @RequestMapping("findById")
    public ModelAndView findById(@RequestParam("id") Integer id){
        ModelAndView mv = new ModelAndView();
        Product product = productService.findById(id);
        mv.addObject("product",product);
        mv.setViewName("product-show");

        return mv ;
    }


    /**
     * 先去找，然后回显
     * @param id
     */
    @RequestMapping("editById")
    public ModelAndView editById(@RequestParam Integer id){
        ModelAndView mv = new ModelAndView();
        Product product = productService.editById(id);
        mv.addObject("product",product);
        mv.setViewName("product-edit");
        return mv;
    }

    //在修改
    @RequestMapping(value = "edit",method = RequestMethod.POST)
    public String edit(Product product){
        //ModelAndView mv = new ModelAndView();
        productService.edit(product);
        return "redirect:findAll.do";
    }
}
